﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace DynCRMMessagingIntegration.Common
{
    public static class SerializationExtensions
    {
        public static string SerializeObject<T>(this T toSerialize)
        {
            using (MemoryStream memStm = new MemoryStream())
            {
                XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(memStm, toSerialize);

                memStm.Seek(0, SeekOrigin.Begin);

                using (var streamReader = new StreamReader(memStm))
                {
                    string result = streamReader.ReadToEnd();
                    return result;
                }
            }
        }

        public static T DeserializeObject<T>(this string xmlObject)
        {
            using (StringReader stringReader = new StringReader(xmlObject))
            {
                using (XmlTextReader xmlReader = new XmlTextReader(stringReader))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    if (serializer.CanDeserialize(xmlReader))
                    {
                        return (T)serializer.Deserialize(xmlReader);
                    }
                    else
                        throw new ArgumentException(string.Format("It was not possible to deserialize the requested message. Type: {0}. Message: {1}", typeof(T).Name, xmlObject));
                }
            }
        }

        public static string GetFirstElementName(this string xmlObject)
        {
            using (StringReader stringReader = new StringReader(xmlObject))
            {
                using (XmlTextReader xmlReader = new XmlTextReader(stringReader))
                {
                    while (xmlReader.Read())
                    {
                        if (xmlReader.IsStartElement())
                        {
                            return xmlReader.Name;
                        }
                    }

                    return string.Empty;
                }
            }
        }

    }
}
